#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash lammps_5Jun2019.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules patch systemd-devel wget
set -e

wget -t 10 -c -P $buildpath https://download.lammps.org/tars/lammps-5Jun2019.tar.gz
tar xf $buildpath/lammps-5Jun2019.tar.gz -C $buildpath && rm -rf $buildpath/lammps-5Jun2019.tar.gz
cp Makefile.mpi.patch $buildpath/lammps-5Jun19/src/MAKE/
cd $buildpath/lammps-5Jun19/src/USER-INTEL
sed -i 18s/immintrin.h/avx2neon.h/ intel_intrinsics_airebo.h
sed -i 746s/immintrin.h/avx2neon.h/ intel_intrinsics_airebo.h
sed -i 1881s/immintrin.h/avx2neon.h/ intel_intrinsics_airebo.h
sed -i 34s/immintrin.h/avx2neon.h/ intel_simd.h
cd ../USER-MGPT
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_mmul3_538.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_mmul3_748.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_mmul3d_526.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_mmul3d_744.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_ttr_5022.c.h
sed -i '21d' mgpt_ttr_5022.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_ttr_5042.c.h
sed -i '21d' mgpt_ttr_5042.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_ttr_7022.c.h
sed -i '21d' mgpt_ttr_7022.c.h
sed -i 19s/xmmintrin.h/avx2neon.h/ mgpt_ttr_7042.c.h
sed -i '21d' mgpt_ttr_7042.c.h
cd $buildpath/lammps-5Jun19/src/MAKE
patch -p0 < ./Makefile.mpi.patch
cd ..
make yes-KSPACE
make yes-MPIIO
make yes-MOLECULE
make yes-MANYBODY
make yes-USER-REAXC
make mpi -j$(nproc)
mkdir -p $installpath/lammps-5Jun2019 && cp -r $buildpath/lammps-5Jun19/* $installpath/lammps-5Jun2019
cat>"$installpath/lammps-5Jun2019/lammps_modulefiles"<<EOF
#%Module1.0
conflict lammps
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set LAMMPS \$pwd
setenv LAMMPS \$LAMMPS
prepend-path PATH \$LAMMPS/src
prepend-path LD_LIBRARY_PATH \$LAMMPS/lib
EOF

rm -rf $buildpath/lammps-5Jun19
